<?php
namespace Admin\Controller;
use Common\Controller\BasicController;
/**
 * 用户管理控制器
 */
class UserAdminController extends BasicController
{
  public function index(){
    $page = $_REQUEST['p']?$_REQUEST['p']:1;
    $pageSize = $_REQUEST['pageSize']?$_REQUEST['pageSize']:10;
    $count = D('User')->getUserCount($map);
    $userList = D('User')->getUserList($page,$pageSize,$map);
    $res = new \Think\Page($count,$pageSize);
    $pageRes = $res->show();
    $this->assign('pageRes',$pageRes);
    $this->assign('list',$userList);
    $this->display();
  }
  public function add(){
    if(IS_POST){
      $info = I('post.');
      if(!trim($info['user_id'])&&!trim($info['username'])){
        return ajaxReturn(400,"用户名必须");
      }
      if(!trim($info['password'])){
        return ajaxReturn(400,"密码必须");
      }
      if(!trim($info['repassword'])){
        return ajaxReturn(400,"确认密码必须");
      }
      if(!trim($info['email'])){
        return ajaxReturn(400,"邮箱必须");
      }
      if($info['password'] !=$info['repassword']){
        return ajaxReturn(400,"两次密码输入不一致");
      }
      if(trim($info['user_id'])){
        return $this->save($info);
      }
      $res = D('User')->addNewUser($info);
      if($res){
        return ajaxReturn(200,"新增用户成功");
      }else{
        return ajaxReturn(400,"新增用户失败，请重试");
      }
    }
    $this->display();
  }
  public function setStatus(){
    if(IS_POST){
      $data = I('post.');
      $id = $data['user_id'];
      unset($data['user_id']);
      $status = $data['status'];
      try{
        $res = D('User')->updateUser($id,$data);
        if($res === false){                 //tp save方法失败返回false，只有false的时候才是失败。
          return ajaxReturn(400,'修改失败');
        }else{
          return ajaxReturn(200,'修改成功');
        }
      }catch(Exception $e){
        return ajaxReturn(400,$e->getMessage());
      }
    }
  }
  public function edit(){
    $id = I('get.id');
    if(!$id){
      $this->error("id不存在");
    }
    $user = D('User')->getUserById($id);
    if(!$user){
      $this->error("id不存在");
    }
    $this->assign('vo',$user);
    $this->display();
  }
  public function save($data){
    $id = $data['user_id'];
    unset($data['user_id']);
    unset($data['username']);
    try{
      $res = D('User')->updateUser($id,$data);
      if($res === false){                 //tp save方法失败返回false，只有false的时候才是失败。
        return ajaxReturn(400,'修改失败');
      }else{
        return ajaxReturn(200,'修改成功');
      }
    }catch(Exception $e){
        return ajaxReturn(400,$e->getMessage());
    }
  }
}
